package com.shengdou.as.slopsapptest.view;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.os.Handler;
import android.os.Message;
import android.util.AttributeSet;
import android.view.View;

import com.shengdou.as.slopsapptest.R;
import com.shengdou.as.slopsapptest.bean.DateBean;
import com.shengdou.as.slopsapptest.utils.LogUtil;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

/**
 * Created by AS on 2016/11/2.
 * 折线图
 */

public class MyChartView extends View {
    private int XPoint = 50;//横坐标
    private int YPoint;//纵坐标

    private int MaxDataSize;//X坐标的刻度个数
    private int MaxYDataSize = 5;//y坐标的刻度个数
    private int XScale; // 刻度长度
    private int YScale;// Y轴刻度长度
    private int YLength;
    private int XLength;//视图宽度

    /**
     * 第一条折线的中间圆点
     */
    private Bitmap lineOneBitmap;
    private List<Float> data;
    private List<Integer> data1;
    private String[] num;
    private String[] Datenum;

    private float[] YLabel;

    private Handler handler = new Handler() {
        public void handleMessage(Message msg) {
            if (msg.what == 0x1234) {
                MyChartView.this.invalidate();
            }
        }

        ;
    };

    public MyChartView(Context context, AttributeSet attrs) {
        super(context, attrs);
        YLabel = new float[6];
        for (int i = 0; i < YLabel.length; i++) {
            YLabel[i] = (float) (i * 1);
        }

        /*new Thread(new Runnable() {

            @Override
            public void run() {
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                if (data.size() > MaxDataSize) {
                    data.remove(0);
                }
                handler.sendEmptyMessage(0x1234);

            }
        }).start();*/
    }

    /**
     * 比onDraw先执行
     * <p>
     * 一个MeasureSpec封装了父布局传递给子布局的布局要求，每个MeasureSpec代表了一组宽度和高度的要求。
     * 一个MeasureSpec由大小和模式组成
     * 它有三种模式：UNSPECIFIED(未指定),父元素部队自元素施加任何束缚，子元素可以得到任意想要的大小;
     * EXACTLY(完全)，父元素决定自元素的确切大小，子元素将被限定在给定的边界里而忽略它本身大小；
     * AT_MOST(至多)，子元素至多达到指定大小的值。
     * <p>
     * 它常用的三个函数：
     * 1.static int getMode(int measureSpec):根据提供的测量值(格式)提取模式(上述三个模式之一)
     * 2.static int getSize(int measureSpec):根据提供的测量值(格式)提取大小值(这个大小也就是我们通常所说的大小)
     * 3.static int makeMeasureSpec(int size,int mode):根据提供的大小值和模式创建一个测量值(格式)
     */
    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        final int minimumWidth = getSuggestedMinimumWidth();
        final int minimumHeight = getSuggestedMinimumHeight();
        LogUtil.e("YView", "---minimumWidth = " + minimumWidth + "");
        LogUtil.e("YView", "---minimumHeight = " + minimumHeight + "");
        XLength = measureWidth(minimumWidth, widthMeasureSpec);
        YLength = measureHeight(minimumHeight, heightMeasureSpec);
        LogUtil.e("YLength+XLength", "XLength = " + XLength + "YLength = " + YLength);
        setMeasuredDimension(XLength, YLength);
        YPoint = YLength - 70;//纵坐标
        YScale = (YPoint - 20) / MaxYDataSize;
    }

    private int measureWidth(int defaultWidth, int measureSpec) {

        int specMode = MeasureSpec.getMode(measureSpec);
        int specSize = MeasureSpec.getSize(measureSpec);
        LogUtil.e("YViewWidth", "---speSize = " + specSize + "");


        switch (specMode) {
            case MeasureSpec.AT_MOST:
                defaultWidth = specSize;

                LogUtil.e("YViewWidth", "---speMode = AT_MOST");
                break;
            case MeasureSpec.EXACTLY:
                LogUtil.e("YViewWidth", "---speMode = EXACTLY");
                defaultWidth = specSize;
                break;
            case MeasureSpec.UNSPECIFIED:
                LogUtil.e("YViewWidth", "---speMode = UNSPECIFIED");
                defaultWidth = Math.max(defaultWidth, specSize);
        }
        return defaultWidth;
    }


    private int measureHeight(int defaultHeight, int measureSpec) {

        int specMode = MeasureSpec.getMode(measureSpec);
        int specSize = MeasureSpec.getSize(measureSpec);
        LogUtil.e("YViewHeight", "---speSize = " + specSize + "");

        switch (specMode) {
            case MeasureSpec.AT_MOST:
                defaultHeight = specSize;
                LogUtil.e("YViewHeight", "---speMode = AT_MOST");
                break;
            case MeasureSpec.EXACTLY:
                defaultHeight = specSize;
                LogUtil.e("YViewHeight", "---speSize = EXACTLY");
                break;
            case MeasureSpec.UNSPECIFIED:
                defaultHeight = Math.max(defaultHeight, specSize);
                LogUtil.e("YViewHeight", "---speSize = UNSPECIFIED");
//        1.基准点是baseline
//        2.ascent：是baseline之上至字符最高处的距离
//        3.descent：是baseline之下至字符最低处的距离
//        4.leading：是上一行字符的descent到下一行的ascent之间的距离,也就是相邻行间的空白距离
//        5.top：是指的是最高字符到baseline的值,即ascent的最大值
//        6.bottom：是指最低字符到baseline的值,即descent的最大值

                break;
        }
        return defaultHeight;


    }

    /**
     * 设置柱状图数据
     */
    public void setColumnInfo(ArrayList<Float> datas) {
        this.data = datas;
        this.postInvalidate();  //可以子线程 更新视图的方法调用。
    }

    /**
     * 设置X轴刻度数据
     */
    public void setXNum(String[] num) {

        this.num = num;
        if (num != null) {
            MaxDataSize = num.length;
            XScale = (XLength - XPoint - 30) / (MaxDataSize + 1);
        }
        this.postInvalidate();  //可以子线程 更新视图的方法调用。
        invalidate();
    }

    /**
     * 设置X轴刻度数据
     */
    public void setXDateNum(String[] num) {

        this.Datenum = num;
        this.postInvalidate();  //可以子线程 更新视图的方法调用。
        invalidate();
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        Paint paint = new Paint();

        Paint xpaint = new Paint();
        Paint xWeekpaint = new Paint();

        Paint mpaint = new Paint();

        Paint mpaint1 = new Paint();

        lineOneBitmap = BitmapFactory.decodeResource(getResources(),
                R.mipmap.lock_open);
        initY(canvas, paint);

        if (num != null && data.size() != 0) {
            if (Datenum == null) {
                initX(canvas, xpaint);//绘制坐标
            }
            if (Datenum != null) {
                initXweekPain(canvas, xWeekpaint);
            }
            drawLineOne(canvas, mpaint);//折线图1
            drawCircle(canvas, mpaint1);//中间的点
        } else {
            initXNull(canvas, xpaint);
        }
//        drawLineTwo(canvas, mpaint1);//  折线图2

        // 绘折线
        /*if (data.size() > 1) {
            for (int i = 1; i < data.size(); i++) {
                canvas.drawLine(XPoint + (i - 1) * XScale, YPoint - data.get(i - 1) *
                        YScale, XPoint + i * XScale, YPoint - data.get(i) * YScale, paint);
            }
        }*/

       /* paint.setStyle(Paint.Style.FILL);
        if (data.size() > 1) {
            Path path = new Path();
            path.moveTo(XPoint, YPoint);
            for (int i = 0; i < data.size(); i++) {
                path.lineTo(XPoint + i * XScale, YPoint - data.get(i) * YScale);
            }
            path.lineTo(XPoint + (data.size() - 1) * XScale, YPoint);
            canvas.drawPath(path, paint);
        }*/
    }

    private void initXweekPain(Canvas canvas, Paint paint) {
        paint.setStyle(Paint.Style.STROKE);
        paint.setAntiAlias(true); // 去锯齿
        paint.setTextSize(20f);
        paint.setColor(Color.WHITE);
        canvas.drawText("时间", XLength - XPoint, YPoint + 30, paint);// X文字
        canvas.drawText("日期", XLength - XPoint, YPoint + 60, paint);// X文字
        for (int i = 0; i < YLabel.length; i++) {
            canvas.drawText(YLabel[i] + "m", XPoint - 50, YPoint - (i) * YScale, paint);//Y轴 文字
        }
        for (int i = 0; i < num.length; i++) {
            canvas.drawLine(XPoint + i * XScale, YPoint, XPoint + i * XScale, YPoint - 5, paint);//X轴 刻度
        }
        //获取时间戳里面的日期及其个数
        ArrayList<DateBean> array = new ArrayList<>();
        Map<String, Integer> map = new HashMap<>();
        for (int i = 0; i < Datenum.length; i++) {
            if (null != map.get(Datenum[i])) {
                map.put(Datenum[i], map.get(Datenum[i]) + 1); // alue+1
            } else {
                map.put(Datenum[i], 1);
            }
        }
        Iterator it = map.entrySet().iterator();
        while (it.hasNext()) {
            DateBean dateBean = new DateBean();
            Map.Entry entry = (Map.Entry) it.next();
            String key = entry.getKey().toString();
            int value = Integer.parseInt(entry.getValue().toString());
            dateBean.setDate(key);
            dateBean.setNum(value);
            array.add(dateBean);
//            System.out.println("key is :" + key + "---value :" + value);
        }
        //将map中的key和value进行排序
        SimpleDateFormat dfs = new SimpleDateFormat("yyyy/MM/dd");
        Calendar c1 = Calendar.getInstance();
        Calendar c2 = Calendar.getInstance();
        String[] DATA = new String[array.size()];
        int[] dataNums = new int[array.size()];
        String temp;
        int nums;
        for (int i = 0; i < array.size(); i++) {
            DATA[i] = array.get(i).getDate();
            dataNums[i] = array.get(i).getNum();
        }

        for (int i = 0; i < DATA.length - 1; i++) {
            for (int j = 0; j < DATA.length - 1 - i; j++) {
                try {
                    c1.setTime(dfs.parse(DATA[j]));
                    c2.setTime(dfs.parse(DATA[j + 1]));
                    int result = c1.compareTo(c2);
//                    System.out.println(DATA[j] + "DATA[j]" + result + "DATA[j + 1]" + DATA[j + 1]);
                    if (result > 0) {
                        temp = DATA[j];
                        nums = dataNums[j];
                        DATA[j] = DATA[j + 1];
                        dataNums[j] = dataNums[j + 1];
                        DATA[j + 1] = temp;
                        dataNums[j + 1] = nums;
                    }
                } catch (ParseException e) {
                    e.printStackTrace();
                }
            }
        }
        //根据日期循环
        int pre = 0;
//        LogUtil.e("DATA.length" + DATA.length);
        for (int i = 0; i < DATA.length; i++) {
            int number = dataNums[i];//不同日期的个数
//            LogUtil.e("======number======", number + "num.length" + num.length);
            String[] numWeek = new String[number];
            String[] DatenumWeek = new String[1];
            if ((DATA.length) % 2 == 0) {
                if (i % 2 == 0) {
                    paint.setColor(Color.WHITE);
                } else {
                    paint.setColor(Color.YELLOW);
                }
            } else {
                if (i % 2 == 0) {
                    paint.setColor(Color.YELLOW);
                } else {
                    paint.setColor(Color.WHITE);
                }
            }
            String date = Datenum[pre].substring(Datenum[pre].indexOf("/") + 1, Datenum[pre].length());
            DatenumWeek[0] = date;
            canvas.drawText(DatenumWeek[0] + "", XPoint + (pre) * XScale, YPoint + 60, paint);// X日期
            for (int j = 0; j < number; j++) {
                LogUtil.e("(i) * number + j", (pre) + "");
                numWeek[j] = num[pre];//将每天的时间根据个数进行添加
                canvas.drawText(numWeek[j], XPoint + (pre) * XScale - 10, YPoint + 30, paint);// X文字
                pre++;
            }

        }
    }

    private void initX(Canvas canvas, Paint paint) {
        paint.setStyle(Paint.Style.STROKE);
        paint.setAntiAlias(true); // 去锯齿
        paint.setColor(Color.WHITE);
        paint.setTextSize(20f);
        canvas.drawText("时间", XLength - XPoint, YPoint + 30, paint);// X文字

        // 添加刻度和文字
        for (int i = 0; i < num.length; i++) {

            canvas.drawText(num[i], XPoint + (i) * XScale - 10, YPoint + 30, paint);// X文字
        }
        if (Datenum != null) {

        }

        for (int i = 0; i < YLabel.length; i++) {
            canvas.drawText(YLabel[i] + "m", XPoint - 50, YPoint - (i) * YScale, paint);//Y轴 文字
        }
        for (int i = 0; i < num.length; i++) {
            canvas.drawLine(XPoint + i * XScale, YPoint, XPoint + i * XScale, YPoint - 5, paint);//X轴 刻度
        }
    }

    private void initXNull(Canvas canvas, Paint paint) {
        paint.setStyle(Paint.Style.STROKE);
        paint.setAntiAlias(true); // 去锯齿
        paint.setColor(Color.WHITE);
        paint.setTextSize(20f);
        canvas.drawText("时间", XLength - XPoint, YPoint + 30, paint);// X文字

        // 添加刻度和文字
        for (int i = 0; i * 80 < (XLength - XPoint - 30); i++) {

            canvas.drawText(i + "", XPoint + i * 80 - 10, YPoint + 30, paint);// X文字
        }
        for (int i = 0; i < YLabel.length; i++) {
            canvas.drawText(YLabel[i] + "m", XPoint - 50, YPoint - (i) * YScale, paint);//Y轴 文字
        }
        for (int i = 0; i * 80 < (XLength - XPoint - 30); i++) {
            canvas.drawLine(XPoint + i * 80, YPoint, XPoint + i * 80, YPoint - 5, paint);//X轴 刻度
        }
    }

    private void initY(Canvas canvas, Paint paint) {
        paint.setStrokeWidth(3);
        paint.setStyle(Paint.Style.STROKE);
        paint.setAntiAlias(true); // 去锯齿
        paint.setColor(0xF0323DA4);
//        paint.setPathEffect(new DashPathEffect(new float[]{5, 5}, 3));//画虚线（1实线，3空白）
        // 画X轴
        canvas.drawLine(XPoint, YPoint, XLength, YPoint, paint);
        // 画y轴
        canvas.drawLine(XPoint, YPoint, XPoint, 0, paint);
        // 添加Y轴刻度和文字//画虚线

        for (int j = 0; j * 15 < XLength; j++) {
            canvas.drawLine(XPoint + ((j) * 15), YPoint - 1 * YScale, XPoint + ((j + 1) * 15) - 5, YPoint - 1
                    * YScale, paint); // 刻度
            canvas.drawLine(XPoint + ((j) * 15), YPoint - 2 * YScale, XPoint + ((j + 1) * 15) - 5, YPoint - 2
                    * YScale, paint); // 刻度
            canvas.drawLine(XPoint + ((j) * 15), YPoint - 3 * YScale, XPoint + ((j + 1) * 15) - 5, YPoint - 3
                    * YScale, paint); // 刻度
            canvas.drawLine(XPoint + ((j) * 15), YPoint - 4 * YScale, XPoint + ((j + 1) * 15) - 5, YPoint - 4
                    * YScale, paint); // 刻度
        }

    }


    //画折线
    private void drawLineOne(Canvas canvas, Paint mpaint) {
        mpaint.setStrokeWidth(2);
        mpaint.setStyle(Paint.Style.STROKE);
        mpaint.setAntiAlias(true); // 去锯齿
        mpaint.setColor(0xF016A76A);
        if (data.size() > 1) {
            Path path = new Path();
            path.moveTo(XPoint, (float) (YPoint - data.get(0) * YScale));
            LogUtil.e("shuju xinxi", XPoint + "=========" + (YPoint - data.get(0) * YScale) + "------" + data.get(0));
            for (int i = 0; i < data.size() - 1; i++) {
                float x1 = XPoint + (i) * XScale;
                float y1 = (float) (YPoint - data.get(i) * YScale);
                float x2 = XPoint + (i + 1) * XScale;
                float y2 = (float) (YPoint - data.get(i + 1) * YScale);
                canvas.drawLine(x1, y1, x2, y2, mpaint);
                path.lineTo(x1, y1);
//                Log.e("xunhuanshuju ", (XPoint + i * XScale) + "===222===" + data.get(i) + "====333====" + (YPoint - data.get(i) * YScale));
                canvas.drawCircle(x2, y2, 1, mpaint);
                canvas.drawCircle(x1, y1, 1, mpaint);
            }
            canvas.drawPath(path, mpaint);

        }
    }

    //画中间的点
    private void drawCircle(Canvas canvas, Paint mpaint) {
        mpaint.setStrokeWidth(10);
        mpaint.setStyle(Paint.Style.STROKE);
        mpaint.setAntiAlias(true); // 去锯齿
        mpaint.setColor(0xF016A76A);
        if (data.size() > 1) {
            Path path = new Path();
            path.moveTo(XPoint, (float) (YPoint - data.get(0) * YScale));
            LogUtil.e("shuju xinxi", XPoint + "=========" + (YPoint - data.get(0) * YScale) + "------" + data.get(0));
            for (int i = 0; i < data.size() - 1; i++) {
                float x1 = XPoint + (i) * XScale;
                float y1 = (float) (YPoint - data.get(i) * YScale);
                float x2 = XPoint + (i + 1) * XScale;
                float y2 = (float) (YPoint - data.get(i + 1) * YScale);
                canvas.drawCircle(x2, y2, 3, mpaint);
                canvas.drawCircle(x1, y1, 3, mpaint);
            }
            canvas.drawPath(path, mpaint);

        } else if (data.size() == 1) {
            Path path = new Path();
            float x1 = XPoint;
            float y1 = (float) (YPoint - data.get(0) * YScale);
            canvas.drawCircle(x1, y1, 3, mpaint);
            canvas.drawPath(path, mpaint);
        }
    }

    private void drawLineTwo(Canvas canvas, Paint mpaint) {
        mpaint.setStrokeWidth(3);
        mpaint.setStyle(Paint.Style.STROKE);
        mpaint.setAntiAlias(true); // 去锯齿
        mpaint.setColor(Color.GREEN);
        if (data1.size() > 1) {
            Path path = new Path();
            path.moveTo(XPoint, YPoint - 1000 / data1.get(0) * YScale);
//            Log.e("shuju xinxi", XPoint + "=========" + (YPoint - data1.get(0) * YScale) + "------" + data1.get(0));
            for (int i = 0; i < data1.size() - 1; i++) {
                int x1 = XPoint + i * XScale;
                int y1 = YPoint - 1000 / data1.get(i) * YScale;
                int x2 = XPoint + (i + 1) * XScale;
                int y2 = YPoint - 1000 / data1.get(i + 1) * YScale;
                canvas.drawLine(x1, y1, x2, y2, mpaint);
                path.lineTo(x1, y1);
//                Log.e("xunhuanshuju ", (XPoint + i * XScale) + "===222===" + data1.get(i) + "====333====" + (YPoint - data1.get(i) * YScale));
                canvas.drawBitmap(lineOneBitmap,
                        x2 - lineOneBitmap.getWidth() / 2,
                        y2 - lineOneBitmap.getHeight() / 2, null);
                canvas.drawBitmap(lineOneBitmap,
                        x1 - lineOneBitmap.getWidth() / 2,
                        y1 - lineOneBitmap.getHeight() / 2, null);
            }
            canvas.drawPath(path, mpaint);

        }
    }
}
